<!--
 * @Author: 宋绍华
 * @Date: 2024-11-11 17:16:16
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-10 10:35:59
 * @FilePath: \sr_system_manager_ui\src\views\project\manage\budgetReview.vue
 * @Description: 预算审核
-->
<template>
  <div class="publish-notices">
    <div class="title">
      {{ route.query.projectName }}
    </div>
    <div class="publish-notices-content">
      <el-form label-width="auto">
        <el-form-item>
          <el-table border :summary-method="getSummaries" show-summary :data="details?.fundingDTOList" style="width: 100%">
            <el-table-column label="序号" width="48">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="budgetAccountName" label="预算科目">
              <template #default="scope">
                {{ scope.row.budgetAccountName }}
              </template>
            </el-table-column>
            <el-table-column prop="fundingProportion" label="经费占比">
              <template #default="scope">
                <span>{{ scope.row.fundingProportion }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="budgetFunding" label="预算经费(万元)">
              <template #default="scope">
                {{ scope.row.budgetFunding }}
              </template>
            </el-table-column>
            <el-table-column prop="memo" label="备注（计算依据与说明）">
              <template #default="scope">
                {{ scope.row.memo }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="预算材料">
          <el-segmented v-model="previewType" :options="opts" style="margin-bottom: 1rem" />
          <FilePreviewMultiple v-if="previewType === 1" :fileList="details.attachmentFileInfoDTOList || []" />
          <el-table v-else border :data="details.attachmentFileInfoDTOList" style="width: 100%">
            <el-table-column prop="name" label="文件名称" />
            <el-table-column prop="createdByName" label="上传人">
              <template #default>
                {{ details?.createdByName }}
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="上传时间" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" link @click="download(scope.row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="审核意见" required>
          <QuickText v-model="form.notices" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="相关文件">
          <FileUpload drag :limit="15" :is-show-tip="false" @update:modelValue="update" :fileSize="10" />
        </el-form-item>
      </el-form>
    </div>
    <div class="publish-notices-btns">
      <el-button type="primary" @click="onEdit">编辑</el-button>
      <el-button @click="onSave">驳回</el-button>
      <el-button type="primary" @click="onPass">通过</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getApproveMaterialDetailsApi, projectApproveApproveApi, projectApproveRejectApi } from '@/api/project';
import { BaseSuccessRespDTO, DictionaryListRespVO, FundingDTO } from '@/api/project/types';
import { TableColumnCtx } from 'element-plus';
import QuickText from '@/components/QuickText/index.vue'
import FilePreviewMultiple from '@/components/FilePreviewMultiple/index.vue'

interface SummaryMethodProps<T = DictionaryListRespVO> {
  columns: TableColumnCtx<T>[]
  data: T[]
}
const previewType = ref(1)
const router = useRouter()
const { proxy } = getCurrentInstance()
const route = useRoute()
const opts = [
  { label: '预览', value: 1 },
  { label: '列表', value: 2 },
]
const form = ref({
  notices: '',
  noticeContent: ''
})

const details = ref<any>({})

// 获取项目详情
const { runAsync: getFundingDetails } = useRequest(getApproveMaterialDetailsApi, {
  manual: true,
  onSuccess: (res) => {
    details.value = res
  }
})

// 通过项目
const { run: projectApproveSubmit } = useRequest(projectApproveApproveApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res.isSuccess) {
      ElMessage({
        message: '提交成功',
        type: 'success',
      })
      // 关闭当前页面
      proxy.$tab.closePage()
    }
  }
})

// 驳回
const { run: projectApproveReject } = useRequest(projectApproveRejectApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res.isSuccess) {
      ElMessage({
        message: '驳回成功',
        type: 'success',
      })
      proxy.$tab.closePage()
    }
  }
})

const tableData = ref([])

// 驳回
const onSave = () => {
  console.log('保存')
  if (form.value.notices === '') {
    ElMessage.error('请填写审核意见')
    return
  }
  projectApproveReject({
    fileIds: details.value.fileIds,
    message: form.value.notices,
    projectId: route.query.projectId as string,
    type: 6
  })
}

// 通过
const onPass = () => {
  console.log('发布')
  if (form.value.notices === '') {
    ElMessage.error('请填写审核意见')
    return
  }
  projectApproveSubmit({
    fileIds: details.value.fileIds,
    message: form.value.notices,
    projectId: route.query.projectId as string,
    type: 6,
    fundingDTOList: tableData.value
  })
}

function update(val) {
  console.log(val)
}

// 计算tableData中的预算经费
const getFundingProportion = (data: FundingDTO[]) => {
  const fundingProportion = data.reduce((prev, curr) => {
    const value = Number(curr.budgetFunding)
    if (!Number.isNaN(value)) {
      return Number(prev) + Number(curr.budgetFunding)
    } else {
      return Number(prev)
    }
  }, 0)
  return fundingProportion
}

// 计算出table 的合计，并显示在最后一行，经费占比输出百分比，根据预算经费得出
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  console.log(data, 'data');

  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = ''
    } else if (index === 1) {
      sums[index] = '合计'
    } else if (index === 2) {
      sums[index] = '100%'
    } else if (index === 3) {
      // 汇总table 中的预算经费
      const _sum = getFundingProportion(details.value?.fundingDTOList || [])
      sums[index] = _sum.toFixed(6)
    }

    return sums
  })
  console.log(sums, 'sums');

  return sums
}

const download = (file) => {
  proxy.$download.downloadFileSync(file?.url, file?.name)
}
// 编辑
const onEdit = () => {
  router.push({ path: '/project/mine/submitBudget', query: {projectId: route.query.projectId, projectName: route.query.projectName, type: 'edit'} })
}

onMounted(() => {
  getFundingDetails({ projectId: route.query.projectId as string, materialType: 2 })
})

</script>

<style lang="scss" scoped>
.publish-notices {
  --at-apply: flex flex-col h-full bg-white;

  .title {
    --at-apply: text-20px font-bold border-b border-#E5E6EB py-16px pl-20px border-b-solid;
  }

  &-content {
    --at-apply: p-30px flex-1 overflow-y-auto;
  }

  &-btns {
    --at-apply: flex py-16px items-center justify-center pt-20px pb-20px;
    border-top: 1px solid #E5E6EB;
  }
}
</style>